const crypto = require('crypto');
const config = require('../../config');
// 日志工具（中国标准时间UTC+8）
const logger = (message) => {
    const now = new Date();
    const chinaTime = new Date(now.getTime() + 8 * 60 * 60 * 1000);
    const chinaTimeStr = chinaTime.toISOString().replace('Z', '+08:00');
    console.log(`[${chinaTimeStr}] ${message}`);
};
// AES-256加密
function encrypt(text) {
    const cipher = crypto.createCipheriv(
        'aes-256-cbc',
        Buffer.from(config.ENCRYPTION_KEY),
        Buffer.from(config.ENCRYPTION_IV)
    );

    let encrypted = cipher.update(text, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return encrypted;
}

// 生成随机密码
function generatePassword() {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let password = '';

    for (let i = 0; i < 16; i++) {
        password += chars.charAt(Math.floor(Math.random() * chars.length));
    }

    return password;
}

// AES-256解密
function decrypt(encryptedText) {
    // 验证输入是否为有效的hex字符串
    if (!/^[0-9a-fA-F]+$/.test(encryptedText) || encryptedText.length % 2 !== 0) {
        logger('无效的加密文本格式，必须是hex字符串');
    }
    
    const decipher = crypto.createDecipheriv(
        'aes-256-cbc',
        Buffer.from(config.ENCRYPTION_KEY),
        Buffer.from(config.ENCRYPTION_IV)
    );

    let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
}

module.exports = { encrypt, decrypt, generatePassword };